#include "swtline.h"

#include <QtQuick/qsgnode.h>
#include <QtQuick/qsgflatcolormaterial.h>
SWTLine::SWTLine(QQuickItem *parent)
    : QQuickItem(parent)
//    , m_p1(10, 10)
//    , m_p2(10, 20)
{
    setFlag(ItemHasContents, true);
}

SWTLine::~SWTLine()
{

}

void SWTLine::setP1(const QPointF &p)
{
    if (p == m_p1)
        return;

    m_p1 = p;
    emit p1Changed(p);
    update();
}
//! [3]

void SWTLine::setP2(const QPointF &p)
{
    if (p == m_p2)
        return;

    m_p2 = p;
    emit p2Changed(p);
    update();
}
QSGNode *SWTLine::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    QSGGeometryNode *node = 0;
    QSGGeometry *geometry = 0;
    if (!oldNode) {
        node = new QSGGeometryNode;
        geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 2);
        geometry->setLineWidth(2);
        geometry->setDrawingMode(GL_LINES);
        node->setGeometry(geometry);
        node->setFlag(QSGNode::OwnsGeometry);
        QSGFlatColorMaterial *material = new QSGFlatColorMaterial;
        material->setColor(Qt::red);
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);
    }else {
        node = static_cast<QSGGeometryNode *>(oldNode);
        geometry = node->geometry();
        geometry->allocate(2);
    }

    QSGGeometry::Point2D *vertices = geometry->vertexDataAsPoint2D();
    vertices[0].set(m_p1.x(),m_p1.y());
    vertices[1].set(m_p2.x(),m_p2.y());
////    vertices[2].set(100,20);
//    vertices[0].set(100,100);
//    vertices[1].set(200,100);
//    vertices[2].set(200,200);
//    vertices[3].set(100,200);
    node->markDirty(QSGNode::DirtyGeometry);
    return node;
}
